import bugtracking.Bug
import java.text.SimpleDateFormat
import bugtracking.History
import bugtracking.ModificationEntry
import bugtracking.Actor
import com.gargoylesoftware.htmlunit.HttpMethod

/**
 * Created by IntelliJ IDEA.
 * User: AlexandruA
 * Date: 7/14/11
 * Time: 3:11 PM
 * To change this template use File | Settings | File Templates.
 */
class HistoryInfoGetter implements Runnable {
    Bug bug;

    HistoryInfoGetter(Bug bug) {
        this.bug = bug;
    }

    public void populateBugHistory(Bug bug, def bugHTML) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
        History history = null;
        ModificationEntry modificationEntry = null;
        def bugzillaBody = bugHTML.'**'.DIV.find {it.@id == "bugzilla-body"};
        if (bugzillaBody.P[1].text().equals("No changes have been made to this bug yet.")) {
            return;
        }
        bugzillaBody.TABLE[0].TBODY[0].eachWithIndex {Node tr, int index ->
            if (index != 0) {
                if (tr.TD[0].@rowspan != null) {
                    history = null;
                    modificationEntry = new ModificationEntry("modifiedProperty": tr.TD[2].text().trim(), "removedValue": tr.TD[3].text().trim(), "addedValue": tr.TD[4].text().trim());                    history = new History("who": new Actor("email": tr.TD[0].text().trim()), "bug_when": sdf.parse(tr.TD[1].text().trim()));
                    history.addToEntries(modificationEntry)
//                    if (bug.history == null) {
//                        bug.history = [history];
//                    } else {
//                        bug.history.add(history)
//                    }
                    bug.addToHistory(history);
                } else {
                    modificationEntry = new ModificationEntry("modifiedProperty": tr.TD[0].text().trim(), "removedValue": tr.TD[1].text().trim(), "addedValue": tr.TD[2].text().trim());
                    history.addToEntries(modificationEntry)
                }
            }
        }
    }

    void run() {
        def url = Configuration.BUGZILLA_URL + Configuration.BUG_ACTIVITY;
        def parser = new org.cyberneko.html.parsers.SAXParser();
        QueryString qs1 = new QueryString(["id": bug.bug_id.toString()]);
        def page = BugzillaConnection.getInstance().createRequest(url, qs1, HttpMethod.GET);
        def bugHTML = new XmlParser(parser).parseText(page.asXml());
        println "before populate " + bug.bug_id
        populateBugHistory(bug, bugHTML);
        println "exit " + bug.bug_id
    }
}
